<?php

namespace App\Helpers\Libraries;

use App\Exceptions\BusinessException;
use App\Helpers\ApiResponse;
use App\Helpers\Enums\ResponseEnum;
use Illuminate\Support\Str;

class OrderLibrary
{
    use ApiResponse;

    /**
     * 生产订单编号
     * @return mixed
     * @throws BusinessException
     */
    public static function createOrderSn()
    {
        return retry(5, function () {
            $orderSn = date('YmdHis').Str::random(6);
            if (!$this->isOrderSnUsed($orderSn)) {
                return $orderSn;
            }
            \Log::warning('订单号获取失败，orderSn:'.$orderSn);
            $this->throwBusinessException(ResponseEnum::HTTP_ERROR, '订单号获取失败');
        });
    }

    /**
     * 校验订单号是否已存在
     * @param $orderSn
     * @return mixed
     */
    public function isOrderSnUsed($orderSn)
    {
        return Order::query()->where('order_sn', $orderSn)->exists();
    }
}
